// Name: Custom_BookInfo
// Description: Allows to modify the info that appears when Book information is called         
// Author: Terisa de Morgan
//
// History:
// 2011-10-29 Terisa - Initial version
// 2012-06-10 Mark Nord - UTF-8 encoding, var-defs, now working in BETA-folder


tmp = function () {
	var opt,
	L = Core.lang.getLocalizer("Custom_BookInfo"),
	log = Core.log.getLogger("Custom_BookInfo"),
	bookChanged = false,
	booklistTrigger = false,
	cols,

	obtenerColeccionesLibro = function (id) {
		var current, coleccion, db, i, id, j, numCol;

		cols = [] ;

		db2 = kbook.model.cache.playlistMasters ;
		db2.sort('indexPlaylist') ;
		numCol = db2.count () ;

		// Busco el libro en todas las colecciones
		//
		for (i = 0; i < numCol; i++)
		{
			coleccion = db2.getRecord (i);
			j = coleccion.getItemIndex(id) + 1;
			if (j) // libro encontrado en la coleccion
			{
				aux = cols.push (coleccion.title) ;
			}
		}

		return (aux) ;
	},
	
	obtenerSerieLibro = function (path) {
		log.error ("Obteniendo series de : " + path) ;
		var serie1 = path.split ("[") ;
		var numSer = serie1.length;

		if (numSer == 1) return '' ;

		var serie2 = serie1[1].split("]") ;
		return serie2[0] 
	},	
	
	obtenerGeneroLibro = function (path) {
		var anthology, serie1, numSer, serie2, indice, genDir, direc ;

		log.error ("Obteniendo genero de : " + path) ;
		indice = path.lastIndexOf('/') ;
		direc = path.substring (1, indice) ;
		log.error ("Direc: " + direc) ;
		indice = direc.lastIndexOf('/') + 1;
		genDir = direc.substring (indice) ;
		log.error ("Direc Genero: " + genDir) ;

		serie1 = genDir.split ("_") ;
		numSer = serie1.length;

		if (numSer == 1) return genDir ;

		log.error ("Serie1: " + serie1[0]) ;
		if (serie1[0] == 'Anthology ')
		{
			indice = genDir.indexOf('_') + 2;
			serie2 = genDir.substring (indice) ;
			return serie2.replace ("_", "/") + "(" + L ("INFO_ANTOL") + ")" ;
		}
		else
		{
			return genDir.replace ("_", "/")
		}
	},	
	
	obtenerAutorLibro = function (author) {
		log.error ("Obteniendo autor de : " + author) ;
		var autor1 = author.split (",") ;
		var numAut = autor1.length;

		if (numAut == 1) return author ;

		if (autor1[1] == '')
			return autor1[0] ;
		else
		{
			res = autor1[1] + ' ' + autor1[0] ;
			return res
		}
	},
	
	// Modifies displayed Book Information:
	
	oldBooksInfo = FskCache.tree.infoListNode.construct;

	FskCache.tree.infoListNode.construct = function () {
		log.error ("Entrando en la funcion de info") ;
		if (opt.InfoStandard == 'true')
		{
			log.error ("Using old construct") ;
			oldBooksInfo.apply (this) ;
		}
		else {
			var colec, media, source, data, prototype, titles, names, formats, c, nodes, i, name, format, value, node, serie, genero;
		log.error ("Cargando info") ;

			media = kbook.model.currentBook.media;

			numCol = obtenerColeccionesLibro (media.id) ;
			log.error ("Tratadas colecciones: " + numCol) ;
			if (opt.InfoSeries == 'true') {
				serie = obtenerSerieLibro (media.path) ;
				log.error ("Serie: " + serie) ;
			}	
			else
				serie="" ;
			genero = obtenerGeneroLibro (media.path) ;
			log.error ("Genero: " + genero) ;

			colec = '' ;

			for (ind = 0; ind < numCol; ind++)
			{
				col1 = cols.shift();
				//col1 = cols[ind];
				log.error ("Coleccion: " + col1) ;
				if (colec == '')
					colec = colec + col1 ;
				else
					colec = colec + ', ' + col1 ;
			}	
		
			source = kbook.model.cache.getSourceByID(media.sourceid);
			data = kbook.bookData;
			prototype = FskCache.tree.infoNode;
			prototype1 = this.prototype ;
			titles = 'fskin:/l/strings/infoTitles'.idToString().split(',');
			//titles=L('INFO_TITLE').split(',');
			log.error ('titles ', titles) ;
			formats = kbook.strings.infoFormats.split(',');
			log.error ('formats ', formats) ;
			//names = this.kbook.strings.infoNames.split(',');
			names = kbook.strings.infoNames.split(',');
			log.error ('names ', names) ;
			c = names.length;
			log.error ('c ', c) ;

			// Obtener colecciones de libro
			//
			i = 0;
			nodes = new Array()
			while (i < c) {
				name = names[i];
				format = formats[i];

				if ((name == 'title') || (name == 'author'))
				{
					log.error ('Pos', i) ;
					log.error ('name : ', name) ;
					log.error ('format : ', format) ;
					if (media.hasOwnProperty(name)) {
						value = media[name];
						log.error ('valor ', value) ;
					}
					else {
						if (data) {
							value = data.getMetadata(name);
						}
					}
					if (name == 'title' && media.isPeriodical()) {
						value = '';
					}

					if (value && (name == 'author'))
					{
						value = obtenerAutorLibro (value) ;
						}
					if (value || format == 'size') {
						log.error ('Analizando 1') ;	
						//prototype1[format];
						//log.error ('Analizando 1a') ;	
						node = xs.newInstanceOf(this.prototypes[format]);
						log.error ('Analizando 2') ;	
						node.cache = this.cache;
						log.error ('Analizando 3') ;	
						node.parent = this;
						log.error ('Analizando 4') ;	
						node.depth = this.depth + 1;
						log.error ('Analizando 5') ;	
						node.name = titles[i];
						log.error ('Analizando 6') ;	
						node.value = node.format(value, source);
						log.error ('Analizando 7') ;	
						nodes.push(node);
						log.error ('Analizando 8') ;	
					}
				}
				i++;
			}

			if (serie != "")
			{
					node = xs.newInstanceOf(this.prototypes['string']);
					node.cache = this.cache;
					node.parent = this;
					node.depth = this.depth + 1;
					node.name = L("INFO_SERIES");
					node.value = node.format(serie, source);
					nodes.push(node);
			}

			if (genero != "")
			{
					node = xs.newInstanceOf(this.prototypes['string']);
					node.cache = this.cache;
					node.parent = this;
					node.depth = this.depth + 1;
					node.name = L("INFO_GENRE");
					node.value = node.format(genero, source);
					nodes.push(node);
			}

			if (colec != "")
			{
					node = xs.newInstanceOf(this.prototypes['string']);
					node.cache = this.cache;
					node.parent = this;
					node.depth = this.depth + 1;
					node.name = L("INFO_COLEC");
					node.value = node.format(colec, source);
					nodes.push(node);
			}
			this.nodes = nodes;
		};
	};	

	var Custom_BookInfo = {
		//name: "Custom_BookInfo", 
		title: L('TITLE'),    
		settingsGroup:"bookmanagement",		//Analogus: add		
		icon: "INFO",
		onInit: function() {
			opt = this.options;
		},
		optionDefs: [{
				name: "InfoStandard",
				title: L("SHOW_STANDARD_INFO"),
				icon: "LIST",
				defaultValue: 'true',
				values: ['true', 'false'],
				valueTitles: {
					'true': L("VALUE_TRUE"),
					'false': L("VALUE_FALSE")
				},
			    },
			    {	    
				name: "InfoSeries",
				title: L("SHOW_SERIES_INFO"),
				icon: "LIST",
				defaultValue: 'true',
				values: ['true', 'false'],
				valueTitles: {
					'true': L("VALUE_TRUE"),
					'false': L("VALUE_FALSE")
				}
			}]
	};

	Core.addAddon(Custom_BookInfo);
};

try {
	kbook.root.children.deviceRoot.children.collections.prototype.by = 'title';
	tmp();
} catch (e) {
	// Core's log
	log.error("in Custom_BookInfo_x50.js", e);
}
